<template>
  <div class="app--account-password">
    <div class="form-box">
      <div class="title">修改密码</div>
      <el-form ref="form" :model="form" :rules="rules" label-position="top" label-width="80px" size="large">
        <el-form-item label="原密码" prop="oldPassword">
          <el-input v-model="form.oldPassword" type="password" />
        </el-form-item>

        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="form.newPassword" type="password" />
        </el-form-item>

        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="form.confirmPassword" type="password" />
        </el-form-item>
      </el-form>
      <div class="form-btn">
        <el-button type="primary" size="large"  :loading="btnLoading" @click="onChange">保存</el-button>
      </div>
    </div>
  </div>
</template>

<script>

export default {
  name: 'PasswordView',
  data () {
    var confirmPassword = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.form.newPassword) {
        callback(new Error('两次输入密码不一致！'))
      } else {
        callback()
      }
    }
    return {
      btnLoading: false,
      form: {
        newPassword: '',
        oldPassword: '',
        confirmPassword: ''
      },
      rules: {
        oldPassword: [
          { required: true, message: '请输入原密码', trigger: 'blur' },
          { min: 6, max: 18, message: '长度在 6 到 18 个字符', trigger: 'blur' }
        ],
        newPassword: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          { min: 6, max: 18, message: '长度在 6 到 18 个字符', trigger: 'blur' }
        ],
        confirmPassword: [
          { validator: confirmPassword, trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    onChange () {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.btnLoading = true
          this.$api('user.password', this.form).then(() => {
            this.$store.dispatch('LogOut').then(() => {
              this.$alert('密码修改成功，请重新登录', {
                showClose: false
              }).then(() => {
                location.reload()
              })
            })
            this.btnLoading = false
          }).catch(() => {
            this.btnLoading = false
          })
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.app--account-password {
  padding: 10px;

  .title {
    text-align: center;
    line-height: 2;
    font-size: 22px;
    margin-top: 20px;
  }

  .form-box {
    max-width: 420px;
    margin: 0 auto;
  }

  .form-btn {
    margin-top: 40px;

    .el-button {
      width: 100%;
    }
  }
}
</style>

